package com.djsblog.background.controller;

import java.util.Date;
import java.util.List;

import com.djsblog.entity.Files;
import com.djsblog.entity.PageBean;
import com.djsblog.entity.User;
import com.djsblog.enums.Options;
import com.djsblog.interceptor.AdminInterceptor;
import com.djsblog.service.UserService;
import com.djsblog.service.impl.FilesServiceImpl;
import com.djsblog.service.impl.UserServiceImpl;
import com.djsblog.util.CodeUtil;
import com.djsblog.util.DataMapUtil;
import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.kit.HashKit;
import com.jfinal.kit.StrKit;

/**
 * 后台用户控制层
 * @author 但劲松
 *
 */
@Before(AdminInterceptor.class)
public class UserController extends Controller{
	private UserService userService = new UserServiceImpl();
	/**
	 * 注销
	 */
	public void logout(){
		getSession().invalidate();
		//清除cookie
		setCookie("user.userName", "", 31622400);
		setCookie("user.password", "", 31622400);
		
		redirect("/index");
	}
	/**
	 * 用户注册
	 */
	public void signUp(){
		User user = getModel(User.class,"user");
		user.setPassword(HashKit.md5(user.getPassword().trim()));
		user.setCreated(new Date());
		if(userService.saveOrUpdate(user)){
			render("/login.jsp");
		}
		render("/login.jsp");
	}
	/**
	 * 登录
	 */
	public void login(){
		User user = getModel(User.class,"user");
		User u = userService.login(user);
		if(u==null||!(u.getPassword().equals(HashKit.md5(user.getPassword().trim())))){
			setAttr("error", "用户名或密码错误");
			setAttr("user", user);
			render("/login.jsp");
		}
		else{
			//System.out.println(getParaToBoolean("remeber"));
			if(getPara("remeber")!=null){
				if(getParaToBoolean("remeber")){
					setCookie("user.userName", user.getUserName(), 31622400);
					setCookie("user.password", user.getPassword(), 31622400);
				}
			}
			setSessionAttr("currentUser", u);
			if("visitor".equals(u.getRole())||"vip".equals(u.getRole()))
				redirect("/index");
			else
				redirect("/back/index");
		}
	}
	/**
	 * 缺省方法
	 */
	public void index(){
		setAttr("mainPage", "/back/user/userTable.jsp");
		setAttr("user", true);
		setAttr("pathNow", "用户列表");
		render("/back/main.jsp");
	}
	/**
	 * ajax验证用户名
	 */
	public void ajaxCheckUserName(){
		String mes = "";boolean state = false;
		String userName = getPara("fieldValue");
		String fieldId = getPara("fieldId");
		if(userService.isExUserName(userName)){ mes="恭喜！该用户名可以使用"; state=true;}
		else mes="用户名已存在";
		renderJson("[\""+fieldId+"\","+state+",\""+mes+"\"]");
	}
	/**
	 * ajax验证信息发送对象的存在否
	 */
	public void ajaxMessageNickName(){
		String mes = "";boolean state = false;
		String nickName = getPara("fieldValue");
		String fieldId = getPara("fieldId");
		if(userService.isExNickName(nickName)) mes="该用户不存在"; 
		else{ mes="✔"; state=true;}
		renderJson("[\""+fieldId+"\","+state+",\""+mes+"\"]");
	}
	/**
	 * ajax验证昵称
	 */
	public void ajaxCheckNickName(){
		String mes = "";boolean state = false;
		String nickName = getPara("fieldValue");
		String fieldId = getPara("fieldId");
		if(userService.isExNickName(nickName)){ mes="恭喜！该昵称可以使用"; state=true;}
		else mes="昵称已存在";
		renderJson("[\""+fieldId+"\","+state+",\""+mes+"\"]");
	}
	/**
	 * ajax列表
	 */
	public void ajaxList(){
		PageBean pageBean = PageBean.creat(getPara("page"), Options.PAGESIZE+"");
		User s_user = getModel(User.class,"s_user");
		List<User> userList = userService.find(s_user , pageBean); 
		long total = userService.count(s_user);
		String[] str = CodeUtil.userBackCode(userList, pageBean, new String[]{total+""});
		setAttr("total", total);
		setAttr("thead", str[0]);
		setAttr("tbody", str[1]);
		setAttr("tfoot", str[2]);
		renderJson();
	}
	/**
	 * 保存
	 */
	public void  ajaxSave(){
		User user = getModel(User.class,"user");
		if(StrKit.notBlank(user.getPassword()))
			if(!(user.getPassword().length()==32))
				user.setPassword(HashKit.md5(user.getPassword().trim()));
		if(user.getId() == null)
			user.setCreated(new Date());
		if(userService.save(user))
			setAttr("success", true);
		else
			setAttr("success", false);
		//更新session中的图片
 		Files s_files = new Files();s_files.setCreated(new Date());
		List<Files> photoWall = new FilesServiceImpl().find(s_files, PageBean.creat("1", "12"));
		setSessionAttr("photoWall", photoWall);
		//更新session中的统计
 		setSessionAttr("data_map", DataMapUtil.updateDataMap());
		//更新session中的当前用户
 		setSessionAttr("currentUser", User.dao.findById(((User)getSessionAttr("currentUser")).getId()));
 		
		renderJson();
	}
	/**
	 * 删除恢复
	 */
	public void ajaxDeleteOrComeback(){
		String del = getPara("del");
		String[] ids=getPara("ids").split(",");
		boolean flag = false;
		for(String id:ids)
			flag=userService.deleteOrComeback(Long.parseLong(id), del);
		if(flag)
			setAttr("success", true);
		else
			setAttr("success", false);
		renderJson();
	}
	
	/**
	 * 获取实体
	 */
	public void ajaxGetById(){
		User user = userService.getById(getParaToLong("id"));
		setAttr("user", user);
		renderJson();
	}
}
